package com.snakegame.controller;

import com.snakegame.dto.JwtResponse;
import com.snakegame.dto.LoginRequest;
import com.snakegame.dto.RegisterRequest;
import com.snakegame.service.AuthService;
import com.snakegame.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController
@RequestMapping("/api/auth")
@CrossOrigin(origins = "*", maxAge = 3600)
public class AuthController {

    @Autowired
    private AuthService authService;

    @Autowired
    private UserService userService;

    @PostMapping("/register")
    public ResponseEntity<?> registerUser(@Valid @RequestBody RegisterRequest registerRequest) {
        try {
            if (userService.existsByUsername(registerRequest.getUsername())) {
                return ResponseEntity.badRequest().body("用户名已存在");
            }

            var user = authService.registerUser(registerRequest);
            return ResponseEntity.ok("用户注册成功");
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    @PostMapping("/login")
    public ResponseEntity<?> authenticateUser(@Valid @RequestBody LoginRequest loginRequest) {
        try {
            String jwt = authService.authenticateUser(loginRequest);
            var user = userService.findByUsername(loginRequest.getUsername()).orElse(null);
            
            if (user == null) {
                return ResponseEntity.badRequest().body("用户不存在");
            }

            return ResponseEntity.ok(new JwtResponse(jwt, user.getUsername(), user.getHighestScore()));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("用户名或密码错误");
        }
    }
}